package kr.hkit.androidproject_caloriecheck;

import java.util.ArrayList;

import kr.hkit.androidproject_caloriecheck.R;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ExerciseFragment extends Fragment {	
	DBHelper mHelper;
	DAO dao;
	ListView list;
	EditText edit;
	Button search;
	String exerciseName;
	int exerciseKcal;
	int exerciseSum;
	ArrayList<MyItem> exercise = new ArrayList<>();
	MyItem exerciseItem;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View root = inflater.inflate(R.layout.exercise_add, container, false);
		
		SharedPreferences pref = getActivity().getSharedPreferences("num", 0);
		exerciseSum = pref.getInt("exerciseSum", exerciseSum);
		
		mHelper = new DBHelper(getActivity());
		dao = DAO.open(getActivity());
		list = (ListView) root.findViewById(R.id.list_exercise);
		edit = (EditText) root.findViewById(R.id.edit_exercise_add);
		search = (Button) root.findViewById(R.id.btn_exercise_search);
		search.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ArrayList<MyItem> arList;
				String exerciseName = edit.getText().toString().trim();
				
				if(exerciseName.equals("")){
					arList = dao.exerciseSelectAll();
				}else{
					arList = dao.exerciseSelectByName(exerciseName);
				}

				if(arList.size() == 0){
					final LinearLayout linear = (LinearLayout) View.inflate(getActivity(), R.layout.exercise_add02, null);					
					
					new AlertDialog.Builder(getActivity())
					.setTitle("검색결과없음")
					.setView(linear)
					.setPositiveButton("추가", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							EditText exerciseName = (EditText) linear.findViewById(R.id.edit_exercisename);
							EditText exerciseCal = (EditText) linear.findViewById(R.id.edit_esercisecal);
							
							String name = exerciseName.getText().toString().trim();
							String cal = exerciseCal.getText().toString().trim();
							
							try {
								validCheck(name, cal);
								dao.exerciseInsert(name, Integer.parseInt(cal));
								Toast.makeText(getActivity(), name + " " + cal +" 추가", Toast.LENGTH_SHORT).show();
								edit.setText("");
							} catch (Exception e) {
								Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
							}

						}
					})
					.setNegativeButton("취소", null)
					.show();
					
				}else{
					MyListAdapter adapter = new MyListAdapter(getActivity(), arList, R.layout.list);
					ListView myList = (ListView) root.findViewById(R.id.list_exercise);
					myList.setAdapter(adapter);
				}				
			}
		});
		
		return root;
	}
	
	public void validCheck(String name, String cal) throws Exception {
		if(name.equals("")){
			throw new Exception("운동명을 입력해주세요.");
		}
		if(cal.equals("")){
			throw new Exception("칼로리를 입력해주세요.");
		}
		
		ArrayList<MyItem> arList = dao.exerciseSelectByName(name);
		if(arList.size() != 0){
			throw new Exception("이미 등록된 정보입니다.");
		}
	}
	
	class MyListAdapter extends BaseAdapter {
		Context maincon;
		LayoutInflater inflater;
		ArrayList<MyItem> arList;
		int layout;
		int mSelect;
		
		public MyListAdapter(Context context, ArrayList<MyItem> arList, int layout) {
			this.maincon = context;
			this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.arList = arList;
			this.layout = layout;
		}

		public int getCount() {
			return arList.size();
		}

		public Object getItem(int position) {
			return arList.get(position).getName();
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			
			if(convertView == null){
				convertView = inflater.inflate(layout, parent, false);
			}
			
			TextView name = (TextView) convertView.findViewById(R.id.name);
			name.setText(arList.get(position).getName());
			
			TextView kcal = (TextView) convertView.findViewById(R.id.kcal);
			kcal.setText(String.valueOf(arList.get(position).getKcal()));
			
			Button add = (Button) convertView.findViewById(R.id.add);
			add.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {				
					new AlertDialog.Builder(getActivity())
					.setTitle("운동 시간을 선택하세요.")
					.setSingleChoiceItems(R.array.time, mSelect, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							mSelect = which;
						}
					})
					.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {							
							switch(mSelect){
							case 0:
								exerciseKcal = arList.get(pos).getKcal();
								
								break;
							case 1:
								exerciseKcal = arList.get(pos).getKcal() * 2;
								break;
							case 2:
								exerciseKcal = arList.get(pos).getKcal() * 3;
								break;
							case 3:
								exerciseKcal = arList.get(pos).getKcal() * 4;
								break;
							case 4:
								exerciseKcal = arList.get(pos).getKcal() * 5;
								break;
							case 5:
								exerciseKcal = arList.get(pos).getKcal() * 6;
								break;
							}
							
							exerciseName = arList.get(pos).getName();
							exerciseItem = new MyItem(exerciseName, exerciseKcal);
							exercise.add(exerciseItem);
							
							exerciseSum += exerciseKcal;
							
							SharedPreferences pref = getActivity().getSharedPreferences("num", 0);
							SharedPreferences.Editor edit = pref.edit();
							
							edit.putInt("exerciseSum", exerciseSum);
							edit.commit();
												
							for(int i=0; i<exercise.size(); i++){
								Log.d("aaa", exercise.get(i).getName() + " " + exercise.get(i).getKcal());
							}
						}
					})
					.setNegativeButton("취소", null)
					.show();					
				}
			});
			
			return convertView;
		}
	}
}
